<template>
	<div class="app-container">
		<comprehensive-table @selection-change="selectionChange" :columns="column" :data="data" @reset="reset"
			@onSubmit="onSubmit" @custom-size-change="handleCustomSizeChange"
			@custom-select-change="handleCustomSelectChange">
			<template v-slot:btn>
				<div style="display: flex;justify-content: flex-end">
					<el-button type="primary" @click="add"><el-icon>
							<plus />
						</el-icon> 添加</el-button>
					<el-button type="danger" @click="batchDelete"><el-icon>
							<delete />
						</el-icon>删除</el-button>
				</div>
			</template>
			<!-- <template v-slot:sex="scope">{{scope.row.sex?'男':'女'}}</template> -->
			<template v-slot:operation="scope">
				<el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
					编辑
				</el-button>
				<el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
					删除
				</el-button>
			</template>
		</comprehensive-table>

		<el-dialog :visible.sync="dialogVisible" :title="title" width="50%">
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
				:size="formSize">
				<el-form-item label="垃圾名称" prop="name">
					<el-input v-model="ruleForm.name" />
				</el-form-item>
				<el-form-item label="所属类型" prop="sort">
					<el-select v-model="ruleForm.sort" placeholder="请选择所属类型">
						<el-option label="可回收垃圾" value="可回收垃圾"></el-option>
						<el-option label="有害垃圾" value="有害垃圾"></el-option>
						<el-option label="厨余垃圾" value="厨余垃圾"></el-option>
						<el-option label="其它垃圾" value="其它垃圾"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleClose('ruleFormRef')">确定</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>
<script>
	var dayjs = require('dayjs')
	import ComprehensiveTable from './components/comprehensive.vue'
	import axios from 'axios'
	const data = []
	// for(let i=0;i<100;i++){
	//   data.push({
	//     name: '香蕉'+i,
	//     id:i+1,
	//     sort:'可回收垃圾'+i
	//   })
	// }
	const column = [{
			type: 'selection',
			width: 150
		},
		{
			name: 'id',
			label: 'id'
		},
		{
			name: 'name',
			label: '垃圾名称',
			inSearch: true,
			valueType: 'input'
		},
		{
			name: 'sort',
			label: '所属类型',
			inSearch: true,
			valueType: 'input'
		},
		{
			name: 'operation',
			slot: true,
			fixed: 'right',
			width: 200
		}
	]
	export default {
		components: {
			ComprehensiveTable
		},
		data() {
			return {
				data,
				column,
				formSize: 'default',
				ruleForm: {
					name: '',
					sort: '',
				},
				rules: {
					name: [{
							required: true,
							message: '请输入垃圾名称',
							trigger: 'blur'
						},

					],
					sort: [{
						required: true,
						message: '请选择性别',
						trigger: 'change',
					}],
				},
				dialogVisible: false,
				title: '新增',
				rowObj: {},
				selectObj: [],
				pageSize: 10,
			}
		},
		created() {
			this.fetchData();
		},
		methods: {
			fetchData() {
				axios.get('http://43.136.172.73/api/v1/rubbish/list', {
						headers: {
							Authorization: ''
						}
					})
					.then(response => {
						// console.log(response);
						const arrData = response.data;
						// console.log(arrData);
						const newData = arrData.map(item => ({
							id: item.id,
							name: item.name,
							sort: item.rubbishCategoryId == 7 ? "可回收垃圾" : (item.rubbishCategoryId == 8 ?
								"有害垃圾" : (item.rubbishCategoryId == 9 ? "厨余垃圾" : "其它垃圾")),
						}));
						// console.log(newData);
						this.data = newData;
						// console.log(this.data);
					})
					.catch(error => {
						console.error('Error:', error);
					});
			},
			async handleClose(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (valid) {
							let obj = {
								// id:Date.now(),
								...this.ruleForm,

							}
							if (this.title === '新增') {
								this.data = [obj, ...this.data]
								console.log(obj);
								obj.sort = obj.sort == "可回收垃圾" ? 7 : (obj.sort == "有害垃圾" ? 8 : (obj.sort ==
									"厨余垃圾" ? 9 : 10));

								axios.post('http://43.136.172.73/api/v1/rubbish', {
										name: obj.name,
										rubbishCategoryId: obj.sort,
									}, {
										headers: {
											Authorization: ''
										},
									}).then(response => {
										console.log(response.data); // 处理响应结果
										this.$message.success('添加成功');
										this.fetchData();
									})
									.catch(error => {
										console.error(error); // 处理请求错误

									})
							} else {
								//确认编辑
								this.data.forEach(item => {
									if (item.id === this.rowObj.id) {
										item.name = obj.name
										item.sort = obj.sort
									}
								})
								obj.sort = obj.sort == "可回收垃圾" ? 7 : (obj.sort == "有害垃圾" ? 8 : (obj.sort ==
									"厨余垃圾" ? 9 : 10));
								// console.log("obj" , obj);

								axios.put('http://43.136.172.73/api/v1/rubbish/update', {
										name: obj.name,
										rubbishCategoryId: obj.sort,
										id: this.rowObj.id,
									}, {
										headers: {
											Authorization: ''
										}
									})
									.then(response => {
										// console.log(response);
										this.$message.success('修改成功')
										this.fetchData();
									})
									.catch(error => {
										console.error(error);
									})
							}
							this.dialogVisible = false
							console.log('submit!', obj)
						} else {
							console.log('error submit!', fields)
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			add() {
				this.title = '新增'
				this.dialogVisible = true
			},
			batchDelete() {
				if (!this.selectObj.length) {
					return this.$message.error('未选中任何行')
				}
				this.$confirm(
						'你确定要删除选中项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						}
					)
					.then(() => {
						console.log(this.selectObj);
						const idArray = [];
						this.selectObj.map(item => idArray.push(item.id));

						console.log(idArray);
						const url = 'http://43.136.172.73/api/v1/rubbish/deletes';
						axios.delete(url, {
								data: idArray, // 将idArray作为请求体数据
								headers: {
									Authorization: 'dsa'
								},
							}).then(response => {
								// 处理成功响应
								console.log(response);
								this.$message.success('删除成功')
								this.fetchData()
							})
							.catch(error => {
								// 处理错误
							})
					})
					.catch(() => {

					})
			},
			selectionChange(val) {
				this.selectObj = val
			},
			edit(row) {
				this.title = '编辑'
				this.rowObj = row
				this.dialogVisible = true

			},
			del(row) {
				this.$confirm(
						'你确定要删除当前项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						}
					)
					.then(() => {
						console.log(row.id);
						const idArray = [];
						idArray.push(row.id);
						console.log(idArray);
						const url = 'http://43.136.172.73/api/v1/rubbish/deletes';
						axios.delete(url, {
								data: idArray, // 将idArray作为请求体数据
								headers: {
									Authorization: 'dsa'
								},
							}).then(response => {
								// 处理成功响应
								console.log(response);
								this.$message.success('删除成功')
								this.fetchData()
							})
							.catch(error => {
								// 处理错误
							})

					})
					.catch(() => {

					})
			},
			//重置
			reset() {
				this.$message.success('触发重置方法')
				this.fetchData();
			},
			//查询
			onSubmit(childData) {
				console.log(childData);
				const obj = childData;
				if ((['可回收垃圾', '有害垃圾', '厨余垃圾', '其它垃圾'].includes(obj.sort)) || obj.name !== null || obj.name !== "") {
					if (obj.sort === null || obj.name === null || obj.sort === "" || obj.name === "") {
						// 执行函数
						console.log(obj);
						if (obj.sort === null || obj.sort === "") {
							axios.get('http://43.136.172.73/api/v1/rubbish/selectByValue/' + obj.name, {
									headers: {
										Authorization: ''
									}
								})
								.then(response => {
									// console.log(response);
									this.data = response.data.data;
									this.data.map(item => {
										item.sort = item.type
									})
									// console.log(childData);
									this.$message.success('触发查询方法');
								})
								.catch(error => {
									console.error('Error:', error);
								});
						} else if ((['可回收垃圾', '有害垃圾', '厨余垃圾', '其它垃圾'].includes(obj.sort))) {
							axios.get('http://43.136.172.73/api/v1/rubbish/getList/' + obj.sort, {
									headers: {
										Authorization: ''
									}
								})
								.then(response => {
									// console.log(response);
									this.data = response.data.data;
									this.data.map(item => {
										item.sort = item.type
									})
									// console.log(childData);
									this.$message.success('触发查询方法');
								})
								.catch(error => {
									console.error('Error:', error);
								});
						} else {
							this.$message.warning('所属类型:可回收垃圾，有害垃圾，厨余垃圾，其它垃圾');
						}

					} else {
						this.$message.warning('只能输入一个数据，进行单次查询');
					}
				} else {
					this.$message.warning('请正确输入数据 , 所属类型:可回收垃圾，有害垃圾，厨余垃圾，其它垃圾');
				}
			},
			//下方的页数改变时
			handleCustomSizeChange(val) {
				console.log(val);
				this.pageSize = val;
				console.log(this.pageSize);
				const totalPage = Math.ceil(this.totalItems / this.pageSize);
				// 处理当前页超出新的总页数的情况
				if (this.currentPage > totalPage) {
					this.currentPage = totalPage;
				}

			},
			//左边选择中的id
			handleCustomSelectChange(val) {
				console.log(val);
				this.selectObj = val;
			}
		}
	}
</script>
<style scoped>
	.edit-input {
		padding-right: 100px;
	}

	.cancel-btn {
		position: absolute;
		right: 15px;
		top: 10px;
	}
</style>